// app.js
const { auth } = require('./utils/auth')
const storage = require('./utils/storage')
const { request } = require('./utils/request')

App({
  globalData: {
    baseUrl: 'http://localhost:8080/api' // 替换为你的后端API地址
  },

  onLaunch() {
    console.log('App Launch')
    
    // 检查登录状态
    this.checkLoginStatus()
    
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        console.log('wx.login success:', res.code)
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
  },

  onShow() {
    console.log('App Show')
  },

  onHide() {
    console.log('App Hide')
  },

  // 初始化应用
  async initApp() {
    try {
      // 获取系统信息
      this.globalData.systemInfo = wx.getSystemInfoSync()
      
      // 设置请求基础URL
      const baseURL = this.getBaseURL()
      this.globalData.baseUrl = baseURL
      request.setBaseURL(baseURL)
      
      // 加载本地配置
      this.loadLocalConfig()
      
      // 加载系统配置
      await this.loadSystemConfig()
      
      // 检查首次启动
      this.checkFirstLaunch()
      
      // 恢复用户数据
      this.restoreUserData()
      
      console.log('应用初始化完成')
    } catch (error) {
      console.error('应用初始化失败:', error)
      throw error
    }
  },

  // 获取基础URL
  getBaseURL() {
    const accountInfo = wx.getAccountInfoSync()
    const envVersion = accountInfo.miniProgram.envVersion
    
    switch (envVersion) {
      case 'develop':
        return 'http://localhost:8080' // 开发环境
      case 'trial':
        return 'https://test-api.lagain.com' // 体验版
      case 'release':
        return 'https://api.lagain.com' // 正式版
      default:
        return 'https://api.lagain.com'
    }
  },

  // 加载本地配置
  loadLocalConfig() {
    this.globalData.theme = appStorage.getTheme()
    this.globalData.language = appStorage.getLanguage()
    this.globalData.appConfig = appStorage.getAppConfig()
    this.globalData.isFirstLaunch = appStorage.isFirstLaunch()
  },

  // 加载系统配置
  async loadSystemConfig() {
    try {
      const response = await systemApi.getConfig()
      if (response.code === 200) {
        this.globalData.appConfig = { ...this.globalData.appConfig, ...response.data }
        appStorage.setAppConfig(this.globalData.appConfig)
      }
    } catch (error) {
      console.warn('加载系统配置失败:', error)
    }
  },

  // 检查首次启动
  checkFirstLaunch() {
    if (this.globalData.isFirstLaunch) {
      this.setDefaultConfig()
      appStorage.setFirstLaunch(false)
      this.globalData.isFirstLaunch = false
    }
  },

  // 设置默认配置
  setDefaultConfig() {
    if (!appStorage.getTheme()) {
      appStorage.setTheme('light')
    }
    
    if (!appStorage.getLanguage()) {
      const systemInfo = this.globalData.systemInfo
      const language = systemInfo?.language || 'zh-CN'
      appStorage.setLanguage(language)
    }
  },

  // 恢复用户数据
  restoreUserData() {
    this.globalData.userInfo = userStorage.getUserInfo()
    this.globalData.token = userStorage.getToken() || ''
  },

  // 检查登录状态
  async checkLoginStatus() {
    try {
      const isLoggedIn = await auth.checkLoginStatus()
      if (isLoggedIn && this.userInfoReadyCallback) {
        const userInfo = auth.getUserInfo()
        if (userInfo) {
          this.userInfoReadyCallback(userInfo)
        }
      }
    } catch (error) {
      console.error('检查登录状态失败:', error)
    }
  },

  // 处理启动场景
  handleLaunchScene(options) {
    const { scene, query, referrerInfo } = options
    
    console.log('启动场景:', { scene, query, referrerInfo })
    
    switch (scene) {
      case 1007: // 单人聊天会话中的小程序消息卡片
      case 1008: // 群聊会话中的小程序消息卡片
        this.handleShareEntry(query)
        break
      case 1011: // 扫描二维码
        this.handleQRCodeEntry(query)
        break
    }
  },

  // 处理显示场景
  handleShowScene(options) {
    this.recordUserActivity()
  },

  // 处理分享进入
  handleShareEntry(query) {
    if (query.capsuleId) {
      wx.navigateTo({
        url: `/pages/capsule/detail?id=${query.capsuleId}`
      })
    }
  },

  // 处理二维码扫描
  handleQRCodeEntry(query) {
    console.log('二维码参数:', query)
  },

  // 记录用户活跃
  recordUserActivity() {
    const lastActiveTime = storage.get('lastActiveTime')
    const now = Date.now()
    
    if (!lastActiveTime || now - lastActiveTime > 30 * 60 * 1000) {
      storage.set('lastActiveTime', now)
      this.reportUserActivity()
    }
  },

  // 上报用户活跃
  reportUserActivity() {
    console.log('用户活跃记录')
  },

  // 设置网络监听
  setupNetworkListener() {
    wx.getNetworkType({
      success: (res) => {
        this.globalData.networkType = res.networkType
      }
    })
    
    wx.onNetworkStatusChange((res) => {
      this.globalData.networkType = res.networkType
      
      this.networkChangeCallbacks.forEach(callback => {
        callback(res.networkType)
      })
      
      if (res.isConnected) {
        this.checkLoginStatus()
      }
    })
  },

  // 验证token有效性
  async validateToken() {
    try {
      const response = await auth.checkLoginStatus()
      return response
    } catch (error) {
      console.error('Token验证失败:', error)
      this.clearUserData()
      this.redirectToLogin()
      return false
    }
  },

  // 跳转到登录页
  redirectToLogin() {
    wx.redirectTo({
      url: '/pages/login/login'
    })
  },

  // 清除用户数据
  clearUserData() {
    this.globalData.userInfo = null
    this.globalData.token = ''
    userStorage.clearAuthData()
  },

  // 设置用户数据
  setUserData(data) {
    this.globalData.token = data.token
    this.globalData.userInfo = data.userInfo
    
    userStorage.setToken(data.token)
    userStorage.setUserInfo(data.userInfo)
  },

  // 网络请求封装（保持兼容性）
  request(options) {
    const requestConfig = {
      url: options.url,
      method: options.method || 'GET',
      data: options.data,
      header: options.header,
      showLoading: false,
      showError: false
    }
    
    request.request(requestConfig)
      .then(response => {
        options.success && options.success(response)
      })
      .catch(error => {
        options.fail && options.fail(error)
      })
      .finally(() => {
        options.complete && options.complete()
      })
  },

  // 检查更新
  checkUpdate() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      
      updateManager.onCheckForUpdate((res) => {
        console.log('检查更新结果:', res.hasUpdate)
      })
      
      updateManager.onUpdateReady(() => {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          success: (res) => {
            if (res.confirm) {
              updateManager.applyUpdate()
            }
          }
        })
      })
      
      updateManager.onUpdateFailed(() => {
        console.error('更新失败')
      })
    }
  },

  // 监听网络变化
  onNetworkChange(callback) {
    this.networkChangeCallbacks.push(callback)
  },

  // 设置主题
  setTheme(theme) {
    this.globalData.theme = theme
    appStorage.setTheme(theme)
    
    wx.setTabBarStyle({
      color: theme === 'dark' ? '#999999' : '#666666',
      selectedColor: theme === 'dark' ? '#ffffff' : '#007AFF',
      backgroundColor: theme === 'dark' ? '#1f1f1f' : '#ffffff',
      borderStyle: theme === 'dark' ? 'white' : 'black'
    })
  },

  // 获取主题
  getTheme() {
    return this.globalData.theme
  },

  // 上报错误
  reportError(error) {
    console.error('上报错误:', error)
  },

  // 显示错误提示
  showError(message) {
    wx.showToast({
      title: message,
      icon: 'error',
      duration: 2000
    })
  },

  // 显示成功提示
  showSuccess(message) {
    wx.showToast({
      title: message,
      icon: 'success',
      duration: 2000
    })
  },

  // 显示加载提示
  showLoading(title = '加载中...') {
    wx.showLoading({
      title,
      mask: true
    })
  },

  // 隐藏加载提示
  hideLoading() {
    wx.hideLoading()
  }
})